package com.example.skillcinema

import android.app.Application
import androidx.room.Room
import com.example.skillcinema.db.localdb.ApplicationDataBase
import com.example.skillcinema.db.localdb.tables.CollectionEntity
import dagger.hilt.android.HiltAndroidApp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch

@HiltAndroidApp
class App : Application() {
    private val appScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
    lateinit var db: ApplicationDataBase

    override fun onCreate() {
        super.onCreate()
        db = Room.databaseBuilder(
            applicationContext, ApplicationDataBase::class.java, "db"
        ).build()
        initDefaultCollections()
    }

    fun initDefaultCollections() {
        appScope.launch {
            if (db.collectionDao().getAllCollections().isEmpty()) {
                val defaultCollections = listOf(
                    CollectionEntity(
                        name = getString(R.string.local_db_favorite_collection),
                        type = CollectionEntity.CollectionType.FAVORITES,
                        isSystem = true
                    ),
                    CollectionEntity(
                        name = getString(R.string.local_db_watch_later),
                        type = CollectionEntity.CollectionType.WATCHLIST,
                        isSystem = true
                    ),
                    CollectionEntity(
                        name = getString(R.string.watched),
                        type = CollectionEntity.CollectionType.WATCHED,
                        isSystem = true
                    )
                )
                defaultCollections.forEach { db.collectionDao().insertCollection(it) }
            }
        }
    }

    override fun onTerminate() {
        appScope.cancel()
        super.onTerminate()
    }
}